package com.iflytek.http.impl;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.iflytek.http.entity.HandledResult;
import com.iflytek.http.interfaces.Handleable;
import com.iflytek.http.interfaces.OperationListener;

public class GetOperation extends AbstractOperation
{
	public GetOperation(int id, String url, Class<? extends Handleable> handlerClass, OperationListener listener)
	{
		super(id, url, handlerClass, listener);
	}

	protected void handleOperation()
	{
		HttpClient client = new DefaultHttpClient();
		try {
			HttpResponse response = null;
			HttpGet getRequest = new HttpGet(this.url);
			response = client.execute(getRequest);

			StatusLine status = response.getStatusLine();
			int code = status.getStatusCode();
			if (code != 200) {
				OperationListener listener = getOperationListener();
				if (listener != null) {
					sendNotOlayMsg(code, EntityUtils.toString(response.getEntity()));
				}
				return;
			}

			Handleable parser = (Handleable)this.mHandlerClass.newInstance();
			String content = null;
			InputStream is = null;
			if (parser.getContentType() == 1)
				content = EntityUtils.toString(response.getEntity());
			else if (parser.getContentType() == 2) {
				is = response.getEntity().getContent();
			}

			OperationListener listener = getOperationListener();

			if (listener == null) {
				System.out.println("activity null");
				if ((this.cacheKey == null) || (this.cacher == null)) {
					return;
				}
				HandledResult result = parse(content, is);
				this.cacher.cache(this.cacheKey, result);
			}
			else {
				HandledResult result = parse(content, is);
				sendSuccessMsg(result);
			}
			if (is != null)
				is.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			sendExceptionMsg(e);
		} catch (Exception e) {
			sendExceptionMsg(e);
		}
	}
}